use napi_derive_ohos::napi;
use napi_ohos::{Either, bindgen_prelude::Uint8Array};
use sha2::Digest;

#[napi]
pub struct Sha224 {
    inner: sha2::Sha224,
}

#[napi]
impl Sha224 {
    #[napi]
    pub fn create() -> Self {
        Self {
            inner: Default::default(),
        }
    }

    #[napi]
    pub fn update(&mut self, buf: Either<String, &[u8]>) {
        self.inner.update(buf);
    }

    #[napi]
    pub fn reset(&mut self) {
        self.inner.reset();
    }

    #[napi]
    pub fn hex(&self) -> String {
        let result = self.inner.clone().finalize();
        format!("{:x}", result)
    }

    #[inline]
    fn buffer(&self) -> Uint8Array {
        let result = self.inner.clone().finalize();
        Uint8Array::from(result.to_vec())
    }

    #[napi]
    pub fn digest(&self) -> Uint8Array {
        self.buffer()
    }

    #[napi]
    pub fn array(&self) -> Uint8Array {
        self.buffer()
    }

    #[napi]
    pub fn array_buffer(&self) -> Uint8Array {
        self.buffer()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn case1() {
        let mut hasher = Sha224::create();
        hasher.update(Either::B(b"hello "));
        hasher.update(Either::B(b"world"));
        let hash = hasher.hex();
        assert_eq!(
            "2f05477fc24bb4faefd86517156dafdecec45b8ad3cf2522a563582b",
            hash
        );
    }
}
